package dao;

import pojo.Carousel;
import utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CarouselDAO {

    private static final String TABLE_NAME = "tb_carousel";

    // 获取所有轮播图
    public static List<Carousel> getAllCarousels() throws SQLException {
        List<Carousel> carousels = new ArrayList<>();
        String sql = "SELECT * FROM " + TABLE_NAME;
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql);
        while (resultSet.next()) {
            Carousel carousel = createCarouselFromResultSet(resultSet);
            carousels.add(carousel);
        }
        return carousels;
    }

    // 根据ID获取轮播图
    public static Carousel getCarouselById(int id) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE carousel_id = ?";
        ResultSet resultSet = (ResultSet) JDBCUtils.execute(sql, id);
        if (resultSet.next()) {
            return createCarouselFromResultSet(resultSet);
        }
        return null;
    }

    // 创建Carousel对象从ResultSet
    private static Carousel createCarouselFromResultSet(ResultSet resultSet) throws SQLException {
        int carouselId = resultSet.getInt("carousel_id");
        String title = resultSet.getString("title");
        String description = resultSet.getString("description");
        String imageUrl = resultSet.getString("image_url");

        Carousel carousel = new Carousel();
        carousel.setCarouselId(carouselId);
        carousel.setTitle(title);
        carousel.setDescription(description);
        carousel.setImageUrl(imageUrl);
        return carousel;
    }

    // 插入轮播图
    public static void insertCarousel(Carousel carousel) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME + " (title, description, image_url) VALUES (?, ?, ?)";
        JDBCUtils.execute(sql, carousel.getTitle(), carousel.getDescription(), carousel.getImageUrl());
    }

    // 更新轮播图
    public static void updateCarousel(Carousel carousel) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET title = ?, description = ?, image_url = ? WHERE carousel_id = ?";
        JDBCUtils.execute(sql, carousel.getTitle(), carousel.getDescription(), carousel.getImageUrl(), carousel.getCarouselId());
    }

    // 删除轮播图
    public static void deleteCarousel(int id) throws SQLException {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE carousel_id = ?";
        JDBCUtils.execute(sql, id);
    }
}
